//
//  FavoriteJobs.swift
//  hello
//
//  Created by 赵康 on 2025/4/15.
//

import Vapor
import Queues
import Fluent

// 定期检查收藏数据一致性的任务
struct FavoriteConsistencyJob: AsyncScheduledJob {
  func run(context: QueueContext) async throws {
    let logger = Logger(label: "FavoriteConsistencyJob")
    
    let users = try await User.query(on: context.application.db).all()
    
    for user in users {
      do {
        // 1. 检查用户是否有默认收藏夹，如果没有则创建
        let defaultFolder = try await getOrCreateDefaultFolder(user: user, db: context.application.db)
        
        // 2. 检查所有收藏是否都有关联的收藏夹，如果没有则关联到默认收藏夹
        let favoritesWithoutFolder = try await Favorite.query(on: context.application.db)
          .filter(\.$user.$id == user.id!)
          .filter(\.$isDeleted == false)
          .filter(\.$folder.$id == nil)
          .all()
        
        if !favoritesWithoutFolder.isEmpty {
          logger.info("为用户 \(user.id!.uuidString) 修复 \(favoritesWithoutFolder.count) 个没有关联收藏夹的收藏")
          for favorite in favoritesWithoutFolder {
            favorite.$folder.id = defaultFolder.id!
            try await favorite.save(on: context.application.db)
          }
        }
        
        // 3. 更新所有收藏夹的专辑计数
        let folders = try await Folder.query(on: context.application.db)
          .filter(\.$user.$id == user.id!)
          .all()
        
        for folder in folders {
          let count = try await Favorite.query(on: context.application.db)
            .filter(\.$folder.$id == folder.id!)
            .filter(\.$user.$id == user.id!)
            .filter(\.$isDeleted == false)
            .count()
          
          logger.debug("用户 \(user.id!.uuidString) 的收藏夹 \(folder.name) 包含 \(count) 个专辑")
        }
      } catch {
        logger.error("处理用户 \(user.id!.uuidString) 的收藏夹数据时发生错误: \(error)")
      }
    }
  }
  
  // 获取或创建默认收藏夹
  private func getOrCreateDefaultFolder(user: User, db: Database) async throws -> Folder {
    // 查找用户的默认收藏夹
    if let defaultFolder = try await Folder.query(on: db)
      .filter(\.$user.$id == user.id!)
      .filter(\.$isDefault == true)
      .first() {
      return defaultFolder
    }
    
    // 创建默认收藏夹
    let defaultFolder = Folder(
      name: "默认收藏夹",
      isDefault: true,
      userID: user.id!
    )
    
    try await defaultFolder.save(on: db)
    return defaultFolder
  }
}

